import { Injectable } from '@nestjs/common'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { CreateContractDto } from './dto/create-contract.dto'
import { UpdateContractDto } from './dto/update-contract.dto'
import { Contract } from './entities/contract.entity'
import { Staff } from '../staff/entities/staff.entity'
const moment = require('moment')

@Injectable()
export class ContractService {
  constructor(
    @InjectRepository(Contract)
    private readonly contract: Repository<Contract>,
    @InjectRepository(Staff)
    private readonly staff: Repository<Staff>
  ) {}
  async create(createContractDto: CreateContractDto) {
    const contract = new Contract()
    const staff = await this.staff.findOne({
      where: { id: +createContractDto.staffId }
    })
    contract.staff = staff
    contract.agreed = createContractDto.agreed
    contract.effectiveDate = createContractDto.effectiveDate
    contract.jobDescription = createContractDto.jobDescription
    contract.sign = createContractDto.sign
    return await this.contract.save(contract)
  }

  async findOne(id: number) {
    return await this.contract.findOne({ where: { id } })
  }

  async findOneByStaffId(id: number) {
    const data = await this.contract.find({
      where: { staff: { id } },
      relations: ['staff', 'staff.job', 'staff.department'],
      order: { id: 'DESC' },
      take: 1
    })
    return {
      id: data[0].id,
      jobDescription: data[0].jobDescription,
      agreed: data[0].agreed,
      effectiveDate: data[0].effectiveDate,
      sign: data[0].sign,
      staff: {
        id: data[0].staff.id,
        name: data[0].staff.name,
        basisSalary: data[0].staff.basisSalary
      },
      job: {
        id: data[0].staff.job.id,
        name: data[0].staff.job.name
      },
      department: {
        id: data[0].staff.department.id,
        name: data[0].staff.department.name
      }
    }
  }

  async update(id: number, updateContractDto: UpdateContractDto) {
    return await this.contract.update(id, updateContractDto)
  }
}
